package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;

import com.sgb.capital.R;
import com.sgb.capital.api.CapitalManager;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.ActivityAddPresonBankCardBinding;
import com.sgb.capital.model.AddAndEditCardsBean;
import com.sgb.capital.model.BankEntity;
import com.sgb.capital.model.BaseEntity;
import com.sgb.capital.model.VCodeEntity;
import com.sgb.capital.utils.CryptoUtils;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.CardsListPop;
import com.sgb.capital.view.pop.ExplanatoryInfoPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.AddAndEditCardsModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import razerdp.basepopup.BasePopupWindow;


/**
 * 作者:陈方凯
 * 日期:2021/5/12
 * 说明:新增个人银行卡
 */
public class AddPersonBankCardActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private ActivityAddPresonBankCardBinding mBinding;
    private AddAndEditCardsModel mModel;
    //支付
    private AddAndEditCardsBean mAndEditCardsBean = new AddAndEditCardsBean();
    //提现
    private VCodeEntity vCodeEntity = new VCodeEntity();

    //绑定银行卡说明弹窗
    private ExplanatoryInfoPop explanatoryInfoPop;
    private TipPop saveSuccessPop, failPop;
    private boolean isPayBankCar = true;
    CardsListPop mListPop;


    public static void start(Context context) {
        Intent intent = new Intent(context, AddPersonBankCardActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        Utils.setStatusBarLightMode(AddPersonBankCardActivity.this, true);
        mBinding = DataBindingUtil.setContentView(AddPersonBankCardActivity.this, R.layout.activity_add_preson_bank_card);
        mModel = new ViewModelProvider(this).get(AddAndEditCardsModel.class);
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.radioGroup.setOnCheckedChangeListener(this);
        mBinding.itemTvCarNum.setInputType(InputType.TYPE_CLASS_NUMBER);
        mBinding.itemTvCarPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        explanatoryInfoPop = new ExplanatoryInfoPop(AddPersonBankCardActivity.this);
        explanatoryInfoPop.setBgView(mBinding.grayLayout);
        mListPop = new CardsListPop(this);
        saveSuccessPop = new TipPop(mContext, "温馨提示", "恭喜您，绑定提现银行卡成功", "", "知道了");
        saveSuccessPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                finish();
            }
        });
        failPop = new TipPop(mContext, "温馨提示", "绑卡只支持借记卡，不支持其他类型银行卡，请重新检查", "", "知道了");
    }

    @Override
    public void initData() {
        mModel.getUserInfo();
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        isPayBankCar = checkedId == R.id.pay_bank_car ? true : false;
        mBinding.itemTvBankType.setHint(checkedId == R.id.pay_bank_car ? "支付银行卡" : "提现银行卡");
        //隐藏显示验证码
        mBinding.rCode.setVisibility(isPayBankCar ? View.GONE : View.VISIBLE);
        //隐藏显示银行卡名称
        mBinding.itemTvBankName.setVisibility(isPayBankCar ? View.VISIBLE : View.GONE);
    }

    /***
     * 支付银行卡数据验证
     */
    private void checkPayData() {
        if (TextUtils.isEmpty(mBinding.itemTvBankName.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvBankName.getHint());
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarNum.getText().toString())) {
            MToast.showLongToast(this, mBinding.itemTvCarNum.getHint().toString());
            return;
        } else if (mBinding.itemTvCarNum.getText().toString().length()<8) {
            MToast.showToast(this, Utils.getString(R.string.capital_bank_error));
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarPhone.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvCarPhone.getHint());
            return;
        } else if (!Utils.isChinaPhoneLegal(mBinding.itemTvCarPhone.getContent().toString())) {
            MToast.showToast(this, Utils.getString(R.string.capital_phone_error));
            return;
        }
        // TODO: 2021/6/16 0016 加密 bankCard idCard phone
        mAndEditCardsBean.bankCard = CryptoUtils.encryptAES_ECB(mBinding.itemTvCarNum.getText().toString());
        mAndEditCardsBean.phone = CryptoUtils.encryptAES_ECB(mBinding.itemTvCarPhone.getContent());
        mModel.mCarInfo.setValue(mAndEditCardsBean);
        mModel.payBankCardList(this, mAndEditCardsBean);
    }

    /***
     * 验证码数据验证
     */
    private void checkVCodeData() {
        if (TextUtils.isEmpty(mBinding.itemTvCarNum.getText().toString())) {
            MToast.showLongToast(this, mBinding.itemTvCarNum.getHint().toString());
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarPhone.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvCarPhone.getHint());
            return;
        } else if (!Utils.isChinaPhoneLegal(mBinding.itemTvCarPhone.getContent())) {
            MToast.showToast(this, Utils.getString(R.string.capital_phone_error));
            return;
        }
        vCodeEntity.bankAccountName = mBinding.itemTvAccountName.getHint();
        vCodeEntity.cardId = mBinding.itemTvCarNum.getText().toString();
        vCodeEntity.mobileId = mBinding.itemTvCarPhone.getContent();
        vCodeEntity.userType = "1";
        mModel.getVCode(AddPersonBankCardActivity.this, vCodeEntity);
    }

    /***
     * 提现银行卡数据验证
     */
    private void checkWithdrawalData() {
        if (TextUtils.isEmpty(mBinding.itemTvCarNum.getText().toString())) {
            MToast.showLongToast(this, mBinding.itemTvCarNum.getHint().toString());
            return;
        } else if (TextUtils.isEmpty(mBinding.itemTvCarPhone.getContent())) {
            MToast.showLongToast(this, mBinding.itemTvCarPhone.getHint());
            return;
        } else if (!Utils.isChinaPhoneLegal(mBinding.itemTvCarPhone.getContent())) {
            MToast.showToast(this, Utils.getString(R.string.capital_phone_error));
            return;
        }

        if (TextUtils.isEmpty(mBinding.etCode.getText())) {
            MToast.showToast(mContext, mBinding.etCode.getHint().toString());
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("cardId", mBinding.itemTvCarNum.getText().toString());
        map.put("verifyCode", mBinding.etCode.getText().toString());
        mModel.bandCar(AddPersonBankCardActivity.this, map);
    }

    private void setWithdrawalSuccess(BaseEntity success) {
        if (success.getState().equals(CapitalManager.RESPONSE_OK)) {
            saveSuccessPop.show();
        } else if ("E00000".equals(success.getCode())) {
            MToast.showToast(mContext, "验证码输入错误");
        } else {
            failPop.show();
        }
    }


    @Override
    public void initObserve() {
        mModel.mBank.observe(this, bankEntities -> {
            if (bankEntities == null || bankEntities.size() == 0) return;
            mListPop.mDatas = bankEntities;
            mListPop.mDatas.get(0).isSelect = true;
            mListPop.show();
        });
        mModel.mUserInfo.observe(this, userInfoEntity -> {
            mBinding.itemTvAccountName.setHint(userInfoEntity.realName);
            mBinding.itemTvIdNumber.setHint(userInfoEntity.identityCard.substring(0, 4) + "********" + userInfoEntity.identityCard.substring(userInfoEntity.identityCard.length() - 4));
            // 加密身份证
            mAndEditCardsBean.idCard = CryptoUtils.encryptAES_ECB(userInfoEntity.identityCard);
            // 账户类型：[0个人、1企业]
            mAndEditCardsBean.type = "0";
            // 卡类型(1支持借记/2贷记卡)
            mAndEditCardsBean.cardType = "1";
            // 账户名称
            mAndEditCardsBean.accountName = userInfoEntity.realName;
        });
        mModel.mBaseEntity.observe(this, baseEntity -> setWithdrawalSuccess(baseEntity));

        mModel.code.observe(this, entity -> {
            // 获取验证码
            CountDownTimer mTimer = new CountDownTimer(60000, 1000) {
                public void onTick(long millisUntilFinished) {
                    mBinding.tvGetCode.setEnabled(false);
                    mBinding.tvGetCode.setText("重新获取" + "(" + (millisUntilFinished / 1000) + ")");
                }

                public void onFinish() {
                    mBinding.tvGetCode.setEnabled(true);
                    mBinding.tvGetCode.setText(Utils.getString(R.string.capital_get_code));
                }
            };
            mTimer.start();
        });
    }

    public void initListener() {
        mBinding.okView.setOnClickListener(v -> {
            if (isPayBankCar) {
                checkPayData();
            } else {
                checkWithdrawalData();
            }
        });
        mBinding.tvGetCode.setOnClickListener(v -> {
            checkVCodeData();
        });

        mBinding.itemTvBankName.setOnWholeItemClickListener(v -> {
            if (mListPop.mDatas.size() == 0) {
                mModel.getQpBank(AddPersonBankCardActivity.this);
                return;
            }
            mListPop.show();
        });
        mBinding.ivInfo.setOnClickListener(v -> {
            explanatoryInfoPop.showDownPopwindow(mBinding.grayLayout, false);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Utils.sendMsg(Constants.EVENT_REFRESH, null);
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants
                    .EVENT_SELECT:
                BankEntity data = (BankEntity) event.data;
                mBinding.itemTvBankName.setContent(data.name);
                mAndEditCardsBean.gateId = data.code;
                mAndEditCardsBean.openingBank = data.name;
                break;
        }
    }
}